package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import tt.dz.biz.service.user.IdentityAccountService;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CardErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.vo.IdentityAccountVO;

@Service("rpcIdentityCardService")
public class RPCIdentityCardService
  implements RPCBaseService
{
  @Resource(name="identityAccountService")
  private IdentityAccountService identityAccountService;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
    throws Exception
  {
    String methodName = message.getName();
    if ("queryIdentityCardByNo".equals(methodName)) {
      return queryIdentityCardByNo(request);
    }
    return "";
  }
  
  public Object queryIdentityCardByNo(Object request)
    throws Exception
  {
    JSONObject resObj = new JSONObject();
    try
    {
      Object req = ((GenericRecord)request).get("req");
      JSONObject reqObj = JSON.parseObject(req.toString());
      String cardNo = reqObj.getString("cardNo");
      if (StringUtils.isBlank(cardNo))
      {
        resObj.put("isSuccess", Integer.valueOf(0));
        resObj.put("errorCode", DzErrorCode.CardErrorCode.CARD_NO_IS_NULL.value());
        resObj.put("errorMsg", DzErrorCode.CardErrorCode.CARD_NO_IS_NULL.getDesc());
        return resObj.toJSONString();
      }
      IdentityAccountVO idaccount = this.identityAccountService.queryIdentifyCardByNo(cardNo);
      if (null == idaccount)
      {
        resObj.put("isSuccess", Integer.valueOf(0));
        resObj.put("errorCode", DzErrorCode.CardErrorCode.NOT_FOUND.value());
        resObj.put("errorMsg", DzErrorCode.CardErrorCode.NOT_FOUND.getDesc());
        return resObj.toJSONString();
      }
      resObj.put("isSuccess", Integer.valueOf(1));
      resObj.put("cardState", idaccount.getState());
      resObj.put("cardNo", idaccount.getCardNo());
      return resObj.toJSONString();
    }
    catch (Exception e)
    {
      LogUtil.error("查询身份识别卡异常，参数为：" + request.toString());
      throw e;
    }
  }
}
